package com.game.hall;

import com.game.config.gameserver.GameServer;
import com.game.config.gameserver.GameServerConfig;
import com.game.message.Msg;
import com.game.net.client.jpbsocket.JPbSocketNettyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lizhiwei
 * @createAt Feb 17, 2015
 */
@Component
public class GameServerConnectManager {
	private static Logger logger = LoggerFactory.getLogger(GameServerConnectManager.class);
	private Map<Integer, List<JPbSocketNettyClient>> allServer = new HashMap();

	//@PostConstruct
	public void connect() {
		List<GameServer> list = GameServerConfig.getInstance().getList();
		for (GameServer gameServer : list) {
			Integer key = gameServer.getGameId();
			if (allServer.get(key) == null) {
				allServer.put(key, new ArrayList<JPbSocketNettyClient>());
			}
			List<JPbSocketNettyClient> gameServerList = allServer.get(key);
			try {
				JPbSocketNettyClient nettyClient = new JPbSocketNettyClient();
				nettyClient.init(gameServer.getIp(), gameServer.getPort());
				gameServerList.add(nettyClient);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("初始化游戏服务器链接出错,服务器={},服务器id={}",gameServer.getGameName(),gameServer.getGameId());
			}
		}
	}

	public void sendMsg(Msg msg, int gameId) {
		List<JPbSocketNettyClient> pbNettyClients = allServer.get(gameId);
		for (JPbSocketNettyClient pbNettyClient : pbNettyClients) {
			pbNettyClient.write(msg);
		}
	}
}
